package cn.tedu.v2_1;

import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;
/**
 * duo聊天室 Version  3
 * 客户端基本不变：关闭socket,拓展增加IP
 *                        1.私有化IP
 *                        2.构造器，当前IP进行赋值
 *                        3.任意位置使用IP【读入知道对方IP】
 * 客户端
 */
public class Client {
    private Socket socket;
    private String ip;
    public Client(){
        try {
            socket=new Socket("172.21.69.1",0202);
            ip =socket.getInetAddress().getHostAddress();
        } catch (UnknownHostException e) {
            System.out.println("IP地址有问题，请询问服务器端！");
        } catch (IOException e) {
            System.out.println("客户端主动退出了：断开链接");
        }finally {

        }
    }
    public void start() throws IOException {
        OutputStream os = null;
        OutputStreamWriter osw = null;
        BufferedWriter bw = null;
        PrintWriter pw = null;
        try {
            pw = new PrintWriter(String.valueOf(new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF8"))));
            os = socket.getOutputStream();
            osw = new OutputStreamWriter(os, "UTF8");
            bw = new BufferedWriter(osw);
            pw = new PrintWriter(bw, true);
            System.out.println("客户端用户：请输入文字：");
            Scanner input = new Scanner(System.in);  //测试--控制台输入文本
            while (true) {
                String say = input.nextLine();
                pw.println(say);
                System.out.println("写出完毕");
            }
        } catch (UnsupportedEncodingException e) {
            System.out.println("客户端与服务器端：字符集不一致！");
        } catch(SocketException e) {
            System.out.println("客户端被重置了~");
        } catch (IOException e) {
            System.out.println("客户端断开链接！");
        } finally {
            if (pw != null)
                pw.close();
            if (socket!=null&&!socket.isClosed()) {
                System.out.println("客户端关闭成功！success~");
                try {
                    socket.close();
                } catch (IOException e) {
                    System.out.println("客户端关闭失败0");
                }
            }
        }
    }
    public static void main(String[] args) throws IOException {
        Client client=new Client();
        client.start();
    }
}
